<template>
	<page-layout :title="pageTitle" button-text="保存" button-wrapper-bg-color="#EFEFEF" @back="handleBack" @button-click="handleSave">
		<!-- 确认退出对话框 -->
		<view class="exit-confirm-modal" v-if="showExitConfirm" @click.self="handleCancelExit">
			<view class="exit-confirm-content" @click.stop>
				<view class="exit-confirm-message">当前内容未保存,确定退出?</view>
				<view class="exit-confirm-buttons">
					<view class="exit-confirm-button cancel-button" @click="handleCancelExit">取消</view>
					<view class="exit-confirm-divider"></view>
					<view class="exit-confirm-button exit-button" @click="handleConfirmExit">退出</view>
				</view>
			</view>
		</view>
		
		<!-- 输入字段列表 -->
		<view class="fields-list">
				<!-- 动态字段列表 -->
				<view 
					class="field-item" 
					v-for="(field, index) in fields" 
					:key="field.id"
					:style="getDragStyle(index)"
				>
					<!-- 标签和图标在同一行 -->
					<view class="field-label-row">
						<input 
							class="field-label-input"
							type="text"
							:value="field.label"
							@input="handleLabelInput($event, field, index)"
							placeholder="请输入..."
							@blur="handleLabelBlur(field)"
							@confirm="handleLabelConfirm(field)"
						/>
						<view class="field-actions">
							<!-- 排序图标（上下箭头） - 只在非第一个字段显示 -->
							<view 
								v-if="index > 0"
								class="action-icon sort-icon"
								@touchstart.stop="handleDragStart($event, index)"
								@touchmove.stop="handleDragMove($event, index)"
								@touchend.stop="handleDragEnd($event, index)"
							>
								<view class="arrow-up"></view>
								<view class="arrow-down"></view>
							</view>
							<!-- 更多操作图标（网格） -->
							<view class="action-icon grid-icon" @click.stop="handleFieldMenu(field, index)">
								<view class="grid-dots">
									<view class="dot"></view>
									<view class="dot"></view>
									<view class="dot"></view>
									<view class="dot"></view>
								</view>
							</view>
						</view>
					</view>
					<!-- 输入框在标签下方 -->
					<view class="field-input-wrapper">
						<input 
							class="field-input"
							:type="field.type"
							:placeholder="field.placeholder"
							:value="field.value"
							@input="handleFieldInput($event, field, index)"
							:password="field.type === 'password' && !field.showPassword"
						/>
					</view>
				</view>
				
				<!-- 固定字段：标签（在动态字段下方） -->
				<view class="field-item">
					<!-- 标签和图标在同一行 -->
					<view class="field-label-row">
						<text class="field-label-text">{{ tagField.label }}</text>
					</view>
					<!-- 标签选择器 -->
					<view class="field-input-wrapper tag-select-wrapper" @click="handleTagFieldClick">
						<view class="tag-select-display">
							<text v-if="selectedTags.length === 0" class="tag-placeholder">{{ tagField.placeholder }}</text>
							<text v-else class="tag-selected-text">{{ getSelectedTagsText() }}</text>
						</view>
						<view class="tag-select-arrow">
							<uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
						</view>
					</view>
				</view>
				<view class="add-field-item">
					<view class="add-field-label" @click="handleAddNewField">
						添加新的字段
					</view>
				</view>
		</view>

		<!-- 字段操作弹窗 -->
		<view class="field-menu-mask" v-if="showFieldMenu" @click="closeFieldMenu">
			<view class="field-menu-content" @click.stop>
				<view class="menu-title">{{ currentField ? currentField.label : '' }}</view>
				<view class="menu-item" @click="handleInsertField">
					在下方插入新字段
				</view>
				<view class="menu-item" v-if="currentField && currentField.type === 'password'" @click="handleFillRandomPassword">
					填入随机密码
				</view>
				<view class="menu-item delete" @click="handleDeleteField">
					删除此字段
				</view>
				<view class="menu-item cancel" @click="closeFieldMenu">
					取消
				</view>
				<!-- 底部指示器 -->
				<view class="menu-footer">
					<view class="home-indicator"></view>
				</view>
			</view>
		</view>

		<!-- 标签选择模态 -->
		<tag-select-modal 
			:visible="showTagSelectModal"
			:selected-tags="selectedTags"
			@close="closeTagSelectModal"
			@confirm="handleTagSelectConfirm"
			@add-tag="handleAddTagFromModal"
		></tag-select-modal>
	</page-layout>
</template>

<script>
	import { addAccount, updateAccount, getAccountById } from '@/utils/accountService.js';
	import { getAllTags, addTag } from '@/utils/tagService.js';
		import TagSelectModal from '@/components/Modal/tag-select-modal.vue';
	
	export default {
		components: {
			TagSelectModal
		},
		data() {
			return {
				accountId: null, // 编辑模式下的账号ID
				isEditMode: false, // 是否是编辑模式
				isTemplateMode: false, // 是否是模版模式
				templateAccountId: null, // 模版账号ID
				showFieldMenu: false,
				currentField: null,
				currentFieldIndex: -1,
				draggingIndex: -1,
				dragStartY: 0,
				dragOffsetY: 0,
				dragOverIndex: -1,
				// 动态字段（可以添加、删除、编辑）
				fields: [
					{
						id: 1,
						label: '名称',
						type: 'text',
						placeholder: '请输入...',
						value: '',
						showPassword: false
					},
					{
						id: 2,
						label: '账号',
						type: 'text',
						placeholder: '请输入...',
						value: '',
						showPassword: false
					},
					{
						id: 3,
						label: '密码',
						type: 'password',
						placeholder: '请输入...',
						value: '',
						showPassword: false
					},
					{
						id: 4,
						label: '备注',
						type: 'text',
						placeholder: '请输入...',
						value: '',
						showPassword: false
					}
				],
				// 固定字段（标签字段，永远在最底部）
				tagField: {
					id: 'tag',
					label: '标签',
					type: 'text',
					placeholder: '请选择...',
					value: '',
					showPassword: false,
					isFixed: true
				},
				fieldCounter: 5,
				// 初始数据快照（用于检测是否有改动）
				initialDataSnapshot: null,
				// 是否显示退出确认对话框
				showExitConfirm: false,
				// 选中的标签数组
				selectedTags: [],
				// 是否显示标签选择模态
				showTagSelectModal: false
			}
		},
		computed: {
			pageTitle() {
				if (this.isEditMode) {
					return '编辑账号';
				} else if (this.isTemplateMode) {
					return '添加新账号';
				} else {
					return '添加新账号';
				}
			}
		},
		onLoad(options) {
			// 检查是否是编辑模式
			if (options.accountId && options.accountId !== 'null' && options.accountId !== 'undefined') {
				const accountId = parseInt(options.accountId);
				if (!isNaN(accountId) && accountId > 0) {
					this.accountId = accountId;
					this.isEditMode = true;
				}
			}
			// 检查是否是模版模式
			if (options.template === '1' && options.templateId) {
				const templateId = parseInt(options.templateId);
				if (!isNaN(templateId) && templateId > 0) {
					this.isTemplateMode = true;
					this.templateAccountId = templateId;
				}
			}
		},
		onReady() {
			// 页面渲染完成后加载数据，确保能正确回显
			if (this.isEditMode && this.accountId) {
				// 使用延迟确保DOM完全渲染
				setTimeout(() => {
					this.loadAccountData();
				}, 200);
			} else if (this.isTemplateMode && this.templateAccountId) {
				// 模版模式，加载模版数据（与编辑模式相同的延迟）
				setTimeout(() => {
					this.loadTemplateData();
				}, 200);
			} else {
				// 新建模式，保存初始空数据快照
				this.saveInitialSnapshot();
			}
		},
		methods: {
			loadAccountData() {
				if (!this.accountId) {
					return;
				}
				
				try {
					const account = getAccountById(this.accountId);
					
					if (!account) {
						// uni.showToast({
						// 	title: '账号不存在',
						// 	icon: 'none'
						// });
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
						return;
					}
					
					// 使用Vue.set确保响应式更新，重新创建fields数组
					const updatedFields = this.fields.map((field, index) => {
						const updatedField = { ...field };
						if (field.label === '名称') {
							updatedField.value = account.name || '';
						} else if (field.label === '账号') {
							updatedField.value = account.account || '';
						} else if (field.label === '密码') {
							updatedField.value = account.password || '';
							// 编辑模式下密码显示明文：将type改为text，并设置showPassword为true
							updatedField.type = 'text';
							updatedField.showPassword = true;
						} else if (field.label === '备注') {
							updatedField.value = account.note || '';
						}
						return updatedField;
					});
					
					// 加载自定义字段到表单（包括空值字段）
					if (account.customFields && typeof account.customFields === 'object') {
						Object.keys(account.customFields).forEach(customKey => {
							// 检查是否已存在该字段
							const existingField = updatedFields.find(f => f.label === customKey);
							const customValue = account.customFields[customKey] || '';
							if (existingField) {
								// 如果已存在，更新值（包括空值）
								existingField.value = customValue;
							} else {
								// 如果不存在，添加新字段（包括空值）
								updatedFields.push({
									id: this.fieldCounter++,
									label: customKey,
									type: 'text',
									placeholder: '请输入...',
									value: customValue,
									showPassword: false
								});
							}
						});
					}
					
					// 重新赋值整个数组以确保响应式更新
					this.fields = updatedFields;
					
					// 更新标签字段：将标签字符串转换为数组
					const tagValue = account.tag || '';
					if (tagValue && tagValue.trim() !== '') {
						// 如果是逗号分隔的字符串，转换为数组
						this.selectedTags = tagValue.split(',').map(t => t.trim()).filter(t => t !== '');
					} else {
						this.selectedTags = [];
					}
					this.tagField = {
						...this.tagField,
						value: tagValue
					};
					
					// 强制更新视图
					this.$forceUpdate();
					
					// 保存初始数据快照
					this.saveInitialSnapshot();
				} catch (error) {
					// uni.showToast({
					// 	title: error.message || '加载数据失败',
					// 	icon: 'none'
					// });
				}
			},
			loadTemplateData() {
				if (!this.templateAccountId) {
					return;
				}
				
				try {
					const account = getAccountById(this.templateAccountId);
					
					if (!account) {
						// uni.showToast({
						// 	title: '模版账号不存在',
						// 	icon: 'none'
						// });
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
						return;
					}
					
					// 使用与编辑模式完全相同的方式，重新创建fields数组
					const updatedFields = this.fields.map((field, index) => {
						const updatedField = { ...field };
						if (field.label === '名称') {
							updatedField.value = account.name || '';
						} else if (field.label === '账号') {
							updatedField.value = account.account || account.subtitle || '';
						} else if (field.label === '密码') {
							// 模版模式下显示密码明文（与编辑模式完全相同）
							updatedField.value = account.password || '';
							updatedField.type = 'text';
							updatedField.showPassword = true;
						} else if (field.label === '备注') {
							updatedField.value = account.note || '';
						}
						return updatedField;
					});
					
					// 加载自定义字段到表单（包括空值字段）
					if (account.customFields && typeof account.customFields === 'object') {
						Object.keys(account.customFields).forEach(customKey => {
							// 检查是否已存在该字段
							const existingField = updatedFields.find(f => f.label === customKey);
							const customValue = account.customFields[customKey] || '';
							if (existingField) {
								// 如果已存在，更新值（包括空值）
								existingField.value = customValue;
							} else {
								// 如果不存在，添加新字段（包括空值）
								updatedFields.push({
									id: this.fieldCounter++,
									label: customKey,
									type: 'text',
									placeholder: '请输入...',
									value: customValue,
									showPassword: false
								});
							}
						});
					}
					
					// 重新赋值整个数组以确保响应式更新（与编辑模式保持一致）
					this.fields = updatedFields;
					
					// 更新标签字段：将标签字符串转换为数组
					const tagValue = account.tag || '';
					if (tagValue && tagValue.trim() !== '') {
						// 如果是逗号分隔的字符串，转换为数组
						this.selectedTags = tagValue.split(',').map(t => t.trim()).filter(t => t !== '');
					} else {
						this.selectedTags = [];
					}
					this.tagField = {
						...this.tagField,
						value: tagValue
					};
					
					// 强制更新视图（与编辑模式保持一致）
					this.$forceUpdate();
					
					// 使用 $nextTick 确保 DOM 更新后再保存快照
					this.$nextTick(() => {
						// 保存初始数据快照
						this.saveInitialSnapshot();
					});
				} catch (error) {
					// uni.showToast({
					// 	title: error.message || '加载模版数据失败',
					// 	icon: 'none'
					// });
				}
			},
			saveInitialSnapshot() {
				// 保存当前表单数据的快照
				const fieldsSnapshot = JSON.parse(JSON.stringify(this.fields));
				const tagFieldSnapshot = JSON.parse(JSON.stringify(this.tagField));
				const selectedTagsSnapshot = JSON.parse(JSON.stringify(this.selectedTags));
				this.initialDataSnapshot = {
					fields: fieldsSnapshot,
					tagField: tagFieldSnapshot,
					selectedTags: selectedTagsSnapshot
				};
			},
			hasUnsavedChanges() {
				// 检查是否有未保存的改动
				if (!this.initialDataSnapshot) {
					// 如果没有初始快照，说明还没有加载完成，不阻止返回
					return false;
				}
				
				// 检查字段数量是否变化
				if (this.fields.length !== this.initialDataSnapshot.fields.length) {
					return true;
				}
				
				// 检查每个字段是否有变化
				for (let i = 0; i < this.fields.length; i++) {
					const currentField = this.fields[i];
					const initialField = this.initialDataSnapshot.fields[i];
					
					if (!initialField || 
						currentField.label !== initialField.label ||
						currentField.value !== initialField.value ||
						currentField.type !== initialField.type) {
						return true;
					}
				}
				
				// 检查标签是否有变化（比较数组）
				const currentTagsStr = this.selectedTags.join(',');
				const initialTagsStr = (this.initialDataSnapshot.selectedTags || []).join(',');
				if (currentTagsStr !== initialTagsStr) {
					return true;
				}
				
				// 新建模式下，检查是否有任何字段值或标签变化
				if (!this.isEditMode) {
					// 检查是否有字段有值（除了默认的固定字段标签名）
					const hasAnyValue = this.fields.some(f => {
						// 检查标签是否有变化（除了默认的4个固定字段）
						const isDefaultField = ['名称', '账号', '密码', '备注'].includes(f.label);
						const labelChanged = !isDefaultField && f.label && f.label.trim() !== '';
						const valueChanged = f.value && f.value.trim() !== '';
						return labelChanged || valueChanged;
					}) || (this.tagField.value && this.tagField.value.trim() !== '');
					
					if (hasAnyValue) {
						return true;
					}
				}
				
				return false;
			},
			handleBack() {
				// 检查是否有未保存的改动
				if (this.hasUnsavedChanges()) {
					this.showExitConfirm = true;
				} else {
					uni.navigateBack();
				}
			},
			handleCancelExit() {
				this.showExitConfirm = false;
			},
			handleConfirmExit() {
				this.showExitConfirm = false;
				uni.navigateBack();
			},
			handleDragStart(e, index) {
				// 开始拖动
				this.draggingIndex = index;
				this.dragStartY = e.touches[0].clientY;
				this.dragOffsetY = 0;
				this.dragOverIndex = -1;
			},
			handleDragMove(e, index) {
				if (this.draggingIndex !== index) return;
				
				const currentY = e.touches[0].clientY;
				this.dragOffsetY = currentY - this.dragStartY;
				
				const itemHeight = 120;
				const moveOffset = Math.round(this.dragOffsetY / itemHeight);
				const newIndex = Math.max(0, Math.min(this.fields.length - 1, index + moveOffset));
				
				// 设置目标位置
				if (newIndex !== index) {
					this.dragOverIndex = newIndex;
				} else {
					this.dragOverIndex = -1;
				}
			},
			getDragStyle(index) {
				if (this.draggingIndex === -1) {
					return {};
				}
				
				// 被拖动的项目跟随手指移动
				if (this.draggingIndex === index) {
					return {
						transform: `translateY(${this.dragOffsetY}px)`,
						opacity: 0.8,
						zIndex: 1000
					};
				}
				
				// 计算其他项目需要移动的距离
				const itemHeight = 120;
				let translateY = 0;
				
				if (this.dragOverIndex !== -1 && this.dragOverIndex !== this.draggingIndex) {
					const draggingFrom = this.draggingIndex;
					const draggingTo = this.dragOverIndex;
					
					// 向下拖动
					if (draggingTo > draggingFrom) {
						// 在拖动项目和目标位置之间的项目向上移动
						if (index > draggingFrom && index <= draggingTo) {
							translateY = -itemHeight;
						}
					} 
					// 向上拖动
					else if (draggingTo < draggingFrom) {
						// 在目标位置和拖动项目之间的项目向下移动
						if (index >= draggingTo && index < draggingFrom) {
							translateY = itemHeight;
						}
					}
				}
				
				if (translateY !== 0) {
					return {
						transform: `translateY(${translateY}px)`,
						transition: 'transform 0.2s ease-out'
					};
				}
				
				return {};
			},
			handleDragEnd(e, index) {
				if (this.draggingIndex !== index) return;
				
				// 如果有有效的目标位置，则交换
				if (this.dragOverIndex >= 0 && this.dragOverIndex < this.fields.length && this.dragOverIndex !== index) {
					// 交换数组中的元素
					const fields = [...this.fields];
					const [removed] = fields.splice(index, 1);
					fields.splice(this.dragOverIndex, 0, removed);
					this.fields = fields;
				}
				
				// 重置拖拽状态
				this.draggingIndex = -1;
				this.dragStartY = 0;
				this.dragOffsetY = 0;
				this.dragOverIndex = -1;
			},
			handleMoveUp(field, index) {
				// 向上移动字段（保留作为备用）
				if (index > 0) {
					const fields = [...this.fields];
					const [removed] = fields.splice(index, 1);
					fields.splice(index - 1, 0, removed);
					this.fields = fields;
				}
			},
			handleMoveDown(field, index) {
				// 向下移动字段（保留作为备用）
				if (index < this.fields.length - 1) {
					const fields = [...this.fields];
					const [removed] = fields.splice(index, 1);
					fields.splice(index + 1, 0, removed);
					this.fields = fields;
				}
			},
			handleFieldMenu(field, index) {
				this.currentField = field;
				// 如果是固定字段（tagField），index 为 -1
				this.currentFieldIndex = index;
				this.showFieldMenu = true;
			},
			closeFieldMenu() {
				this.showFieldMenu = false;
				this.currentField = null;
				this.currentFieldIndex = -1;
			},
			handleInsertField() {
				if (this.currentFieldIndex >= 0) {
					const newField = {
						id: this.fieldCounter++,
						label: '新字段',
						type: 'text',
						placeholder: '请输入...',
						value: '',
						showPassword: false
					};
					this.fields.splice(this.currentFieldIndex + 1, 0, newField);
				}
				this.closeFieldMenu();
			},
			handleFillRandomPassword() {
				if (this.currentField) {
					if (this.currentField.type === 'password') {
						// 生成随机密码
						const randomPassword = this.generateRandomPassword();
						this.currentField.value = randomPassword;
					} else {
						// 对于非密码字段，也可以生成随机内容（可选功能）
						// uni.showToast({
						// 	title: '此功能仅适用于密码字段',
						// 	icon: 'none'
						// });
					}
				}
				this.closeFieldMenu();
			},
			generateRandomPassword() {
				const length = 12;
				const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
				let password = '';
				for (let i = 0; i < length; i++) {
					password += charset.charAt(Math.floor(Math.random() * charset.length));
				}
				return password;
			},
			handleDeleteField() {
				// 如果是固定字段（标签），不允许删除
				if (this.currentField && this.currentField.isFixed) {
					// uni.showToast({
					// 	title: '标签字段不能删除',
					// 	icon: 'none'
					// });
					this.closeFieldMenu();
					return;
				}
				
				if (this.currentFieldIndex >= 0 && this.fields.length > 1) {
					this.fields.splice(this.currentFieldIndex, 1);
				}
				this.closeFieldMenu();
			},
			handleAddNewField() {
				const newField = {
					id: this.fieldCounter++,
					label: '',
					type: 'text',
					placeholder: '请输入...',
					value: '',
					showPassword: false
				};
				this.fields.push(newField);
			},
			handleLabelInput(e, field, index) {
				// 处理标签输入，确保响应式更新
				const value = e.detail.value;
				this.$set(this.fields[index], 'label', value);
			},
			handleLabelBlur(field) {
				// 失去焦点时的处理，如果为空则保持为空（显示placeholder）
				// 不做任何处理，让placeholder显示
			},
			handleLabelConfirm(field) {
				// 确认时的处理
				// 不做任何处理，让用户输入标签名称
			},
			handleFieldInput(e, field, index) {
				// 处理字段输入，确保响应式更新
				const value = e.detail.value;
				this.$set(this.fields[index], 'value', value);
			},
			// 点击标签字段，打开选择模态
			handleTagFieldClick() {
				this.showTagSelectModal = true;
			},
			// 关闭标签选择模态
			closeTagSelectModal() {
				this.showTagSelectModal = false;
			},
			// 确认标签选择
			handleTagSelectConfirm(selectedTags) {
				this.selectedTags = selectedTags || [];
				this.showTagSelectModal = false;
			},
			// 从模态中添加新标签
			handleAddTagFromModal() {
				// 关闭标签选择模态
				this.showTagSelectModal = false;
				// 跳转到标签管理页面
				uni.navigateTo({
					url: '/pages/tag-management/tag-management',
					fail: (err) => {
						// uni.showToast({
						// 	title: '跳转失败',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			// 获取选中标签的显示文本
			getSelectedTagsText() {
				if (this.selectedTags.length === 0) {
					return '';
				}
				return this.selectedTags.join('、');
			},
			handleSave() {
				// 验证必填字段
				const nameField = this.fields.find(f => f.label === '名称');
				if (!nameField || !nameField.value || nameField.value.trim() === '') {
					// uni.showToast({
					// 	title: '请输入名称',
					// 	icon: 'none'
					// });
					return;
				}

				// 收集所有字段数据（除了名称、账号、密码、备注之外的自定义字段）
				const customFields = {};
				this.fields.forEach(field => {
					if (field.label && field.label.trim() !== '' && 
						!['名称', '账号', '密码', '备注'].includes(field.label.trim())) {
						// 保存所有自定义字段，包括空值（空值也保存，在详情页显示"无"）
						const fieldValue = field.value ? field.value.trim() : '';
						customFields[field.label.trim()] = fieldValue;
					}
				});
				
				// 编辑模式下，如果原有账号有自定义字段，需要合并保留（保留原有但当前表单中没有的字段）
				if (this.isEditMode && this.accountId) {
					try {
						const existingAccount = getAccountById(this.accountId);
						if (existingAccount && existingAccount.customFields) {
							// 合并原有自定义字段，保留那些在当前表单中不存在的字段
							Object.keys(existingAccount.customFields).forEach(key => {
								if (!customFields.hasOwnProperty(key)) {
									customFields[key] = existingAccount.customFields[key];
								}
							});
						}
					} catch (e) {
						// 忽略错误
					}
				}

				// 处理标签：将选中的标签数组转换为逗号分隔的字符串
				const finalTag = this.selectedTags.length > 0 ? this.selectedTags.join(',') : '';

				// 保存数据
				const accountData = {
					name: nameField.value.trim(),
					account: this.fields.find(f => f.label === '账号')?.value?.trim() || '',
					password: this.fields.find(f => f.label === '密码')?.value || '',
					note: this.fields.find(f => f.label === '备注')?.value?.trim() || '',
					tag: finalTag,
					customFields: customFields // 保存自定义字段
				};

				try {
					if (this.isEditMode && this.accountId) {
						// 编辑模式：更新账号
						updateAccount(this.accountId, accountData);
					} else {
						// 添加模式：创建新账号
						addAccount(accountData);
					}

					// 保存成功后，更新初始快照（避免返回时再次提示）
					this.saveInitialSnapshot();
					
					// 直接返回首页
					uni.reLaunch({
						url: '/pages/index/index'
					});
				} catch (error) {
					// uni.showToast({
					// 	title: error.message || '保存失败',
					// 	icon: 'none'
					// });
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.fields-list {
		flex: 1;
		background-color: #FFFFFF;
		margin-top: 0;
		border-top: 1px solid #F5F5F5;
		border-bottom: 1px solid #F5F5F5;
		display: flex;
		flex-direction: column;
	}

	.field-item {
		padding: 20rpx 32rpx;
		transition: transform 0.1s ease-out;
		position: relative;
	}

	.add-field-item {
		padding: 28rpx 32rpx 60rpx;
		border-top: 1px solid #F5F5F5;
	}

	.add-field-label {
		font-size: 30rpx;
		color: #5A7093;
		text-align: center;
		font-weight: 400;
		line-height: 1.5;
		letter-spacing: 0.3rpx;
	}

	.field-label-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16rpx;
		padding-left: 16rpx;
	}

	.field-label-text {
		font-size: 30rpx;
		color: #333333;
		font-weight: 400;
		flex: 1;
		line-height: 1.5;
		letter-spacing: 0.3rpx;
	}

	.field-label {
		font-size: 30rpx;
		color: #333333;
		font-weight: 400;
		flex: 1;
		line-height: 1.5;
		letter-spacing: 0.3rpx;
	}

	.field-label-input {
		flex: 1;
		font-size: 30rpx;
		color: #333333;
		font-weight: 400;
		background-color: transparent;
		border: none;
		padding: 0;
		margin: 0;
		height: auto;
		line-height: 1.6;
		letter-spacing: 0.3rpx;
		
		&::placeholder {
			color: #999999;
			font-weight: 400;
			opacity: 0.8;
		}
	}

	.field-input-wrapper {
		width: 100%;
	}

	// 标签选择器样式
	.tag-select-wrapper {
		background-color: #F8F8F8;
		border-radius: 8rpx;
		padding: 0 24rpx;
		min-height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: relative;
		cursor: pointer;
		width: 100%;
		box-sizing: border-box;
		overflow: hidden;
	}

	.tag-select-display {
		flex: 1;
		font-size: 30rpx;
		color: #333333;
		min-height: 80rpx;
		display: flex;
		align-items: center;
		overflow: hidden;
		min-width: 0;
	}

	.tag-placeholder {
		color: #999999;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.tag-selected-text {
		color: #333333;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.tag-select-arrow {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 16rpx;
		flex-shrink: 0;
	}

	.field-input {
		width: 100%;
		height: 80rpx;
		background-color: #F8F8F8;
		border-radius: 8rpx;
		padding: 0 24rpx;
		font-size: 30rpx;
		color: #333333;
		line-height: 80rpx;
		box-sizing: border-box;
		letter-spacing: 0.3rpx;
		
		&::placeholder {
			color: #999999;
			opacity: 0.8;
			font-weight: 400;
		}
	}

	.field-actions {
		display: flex;
		align-items: center;
		gap: 24rpx;
		flex-shrink: 0;
		margin-left: 16rpx;
	}

	.action-icon {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 48rpx;
		height: 48rpx;
		padding: 8rpx;
		cursor: pointer;
	}

	.sort-icon {
		flex-direction: column;
		position: relative;
		height: 32rpx;
		justify-content: center;
		align-items: center;
		gap: 4rpx;
		touch-action: none;
		user-select: none;
		cursor: grab;
		
		&:active {
			cursor: grabbing;
		}
	}

	.arrow-up,
	.arrow-down {
		width: 0;
		height: 0;
		border-left: 6rpx solid transparent;
		border-right: 6rpx solid transparent;
		cursor: pointer;
		transition: opacity 0.2s;
		
		&:active {
			opacity: 0.6;
		}
	}

	.arrow-up {
		border-bottom: 8rpx solid #999999;
		margin-bottom: 2rpx;
	}

	.arrow-down {
		border-top: 8rpx solid #999999;
	}

	.grid-icon {
		position: relative;
	}

	.grid-dots {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		grid-template-rows: repeat(2, 1fr);
		gap: 4rpx;
		width: 28rpx;
		height: 28rpx;
	}

	.dot {
		width: 6rpx;
		height: 6rpx;
		background-color: #999999;
		border-radius: 1rpx;
	}

	// 字段操作弹窗
	/* 退出确认对话框样式 */
	.exit-confirm-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 3000;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.exit-confirm-content {
		width: 560rpx;
		background-color: #FFFFFF;
		border-radius: 24rpx;
		overflow: hidden;
	}

	.exit-confirm-message {
		padding: 60rpx 40rpx 48rpx;
		font-size: 32rpx;
		color: #333333;
		text-align: center;
		line-height: 1.5;
	}

	.exit-confirm-buttons {
		display: flex;
		border-top: 1px solid #E5E5E5;
	}

	.exit-confirm-button {
		flex: 1;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		cursor: pointer;
	}

	.cancel-button {
		color: #333333;
	}

	.exit-confirm-divider {
		width: 1px;
		background-color: #E5E5E5;
	}

	.exit-button {
		color: #FF3B30;
	}

	.field-menu-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 2000;
		display: flex;
		align-items: flex-end;
		justify-content: center;
	}

	.field-menu-content {
		width: 100%;
		background-color: #FFFFFF;
		border-radius: 32rpx 32rpx 0 0;
		max-height: 60vh;
		animation: slideUp 0.3s ease-out;
		overflow: hidden;
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}
		to {
			transform: translateY(0);
		}
	}

	.menu-title {
		padding: 40rpx 32rpx 32rpx;
		font-size: 30rpx;
		color: #999999;
		font-weight: 400;
		text-align: center;
		border-bottom: 1px solid #F5F5F5;
		letter-spacing: 0.3rpx;
	}

	.menu-item {
		padding: 32rpx;
		font-size: 30rpx;
		color: #333333;
		min-height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1.5;
		letter-spacing: 0.3rpx;
		border-bottom: 1px solid #F5F5F5;
		
		&.delete {
			color: #FF3B30;
		}
		
		&.cancel {
			border-top: 1px solid #F5F5F5;
			margin-top: 0;
		}
		
		&:last-of-type:not(.cancel) {
			border-bottom: 1px solid #F5F5F5;
		}
	}

	.menu-footer {
		padding: 20rpx 0;
		display: flex;
		justify-content: center;
	}

	.home-indicator {
		width: 80rpx;
		height: 4rpx;
		background-color: #CCCCCC;
		border-radius: 2rpx;
	}
</style>

